from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from sklearn.datasets import load_digits
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  
plt.rcParams['axes.unicode_minus'] = False 

# 加载手写数字数据集
digits = load_digits()
X_digits = digits.data
y_digits = digits.target

print(f"手写数字数据集形状: {X_digits.shape}")

# 数据预处理和分割
X_digits_train, X_digits_test, y_digits_train, y_digits_test = train_test_split(
    X_digits, y_digits, test_size=0.2, random_state=42
)

# 创建复杂管道
digits_pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('dim_reducer', PCA(n_components=0.95)),  # 保留95%的方差
    ('classifier', GradientBoostingClassifier(random_state=42))
])

# 训练和评估
digits_pipeline.fit(X_digits_train, y_digits_train)
digits_accuracy = digits_pipeline.score(X_digits_test, y_digits_test)

print(f"手写数字识别准确率: {digits_accuracy:.4f}")

# 可视化部分结果
plt.figure(figsize=(12, 6))

# 显示一些测试样本
for i in range(10):
    plt.subplot(2, 5, i + 1)
    plt.imshow(X_digits_test[i].reshape(8, 8), cmap='gray')
    pred = digits_pipeline.predict([X_digits_test[i]])
    true = y_digits_test[i]
    plt.title(f'预测: {pred}, 真实: {true}')
    plt.axis('off')

plt.tight_layout()
plt.show()